package com.skyline.imagine.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * Servlet implementation class ImageViewer
 */
public class ImageViewer extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String localPath = "F:\\imagine\\storelocal";
	private static final long CACHE_TIME =  1000L * 3600 * 24 * 365;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ImageViewer() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String uri = request.getRequestURI();
		String filename = uri.substring(uri.lastIndexOf('/')+1);
		if(isModifyed(request, response)) {
			File file = getFileByFilename(filename);
			outputImage(file, request, response);
		} else {
			responseNotModified(request, response);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		this.doGet(request, response);
	}

	private File getFileByFilename(String filename) {
		return new File(localPath, filename);
	}
	
	private boolean isModifyed(HttpServletRequest request, HttpServletResponse response) {
		long lastModified = request.getDateHeader("If-Modified-Since");
		Date now = new Date();
		return (now.getTime() - lastModified) > CACHE_TIME;
	}
	
	private void outputImage(File image, HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setContentType("image/jpeg");
		response.setHeader("Accept-Ranges", "bytes");
		Date now = new Date();
		response.setDateHeader("Last-Modified", now.getTime());
		OutputStream output = response.getOutputStream();
		InputStream input = FileUtils.openInputStream(image);
		IOUtils.copy(input, output);
		IOUtils.closeQuietly(input);
		IOUtils.closeQuietly(output);
	}
	
	private void responseNotModified(HttpServletRequest request, HttpServletResponse response) {
		response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
	}

}
